﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ROrganizer.Client.Crawling
{
    public class LetterPairSimilarity
    {
        private static string[] GetLetterPairs(string text)
        {
            var numPairs = text.Length - 1;
            var pairs = new string[numPairs];

            for (int i = 0; i < numPairs; i++)
                pairs[i] = text.Substring(i, 2);

            return pairs;
        }

        private static IList<string> GetWordLetterPairs(String text)
        {
            var allPairs = new List<string>();
            var words = Regex.Split(text, "\\s");

            for (int w = 0; w < words.Length; w++)
            {
                var pairsInWord = GetLetterPairs(words[w]);

                for (int p = 0; p < pairsInWord.Length; p++)
                    allPairs.Add(pairsInWord[p]);
            }

            return allPairs;
        }

        public static double CompareStrings(String left, String right)
        {
            var lpairs = GetWordLetterPairs(left.ToUpper());
            var rpairs = GetWordLetterPairs(right.ToUpper());
            var intersection = 0;
            var union = lpairs.Count + rpairs.Count;

            for (int i = 0; i < lpairs.Count; i++)
            {
                var pair1 = lpairs[i];

                for (int j = 0; j < rpairs.Count; j++)
                {
                    var pair2 = rpairs[j];

                    if (pair1 == pair2)
                    {
                        intersection++;
                        rpairs.RemoveAt(j);

                        break;
                    }
                }

            }

            return (2.0 * intersection) / union;
        }
    }
}
